package struts.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.config.ActionConfig;
import struts.config.StrutsConfig;
import struts.form.BaseForm;
import struts.parser.ModelParser;

/**
 * Servlet implementation class Action
 */
@WebServlet("/DispatcherAction")
public class DispatcherAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DispatcherAction() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String url = "";
	    String path=getServletPath(request);
	    ActionConfig actionConfig=StrutsConfig.getActionConfig(path);
	    AbstractAction action=actionConfig.getAction();
	    BaseForm baseForm  = ModelParser.parseForm(actionConfig.getRefForm(), request);
	    String typeName=action.execute(baseForm, request, response);
	    url=actionConfig.getUrl(typeName);
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	
	private String getServletPath(HttpServletRequest request) {
		return request.getServletPath().split("//.")[0];
	} 

}
